import 'dart:async';

import 'package:convergence_media/di/di.dart';
import 'package:convergence_media/features/config/constants/database_schemas.dart';
import 'package:convergence_media/features/config/logger/logger.dart';
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppBlocObserver extends ProviderObserver {
  const AppBlocObserver();

  @override
  void didUpdateProvider(
    ProviderBase<Object?> provider,
    Object? previousValue,
    Object? newValue,
    ProviderContainer container,
  ) {
    logger.t('$provider: $previousValue->$newValue');
    super.didUpdateProvider(provider, previousValue, newValue, container);
  }
}

Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
  FlutterError.onError = (details) {
    logger.f(details.exceptionAsString(), stackTrace: details.stack);
  };

  // Add cross-flavor configuration here
  WidgetsFlutterBinding.ensureInitialized();


  final sharedPreferences = await SharedPreferences.getInstance();
  final appDocument = await getApplicationDocumentsDirectory();
  final isar = await Isar.open(schemas, directory: appDocument.path);

  runApp(
    ProviderScope(
      overrides: [
        sharedPreferenceProvider.overrideWithValue(sharedPreferences),
        appDocumentPathProvider.overrideWithValue(appDocument),
        appIsarProvider.overrideWithValue(isar),
      ],
      child: await builder(),
    ),
  );
}
